<?php
namespace app\admin\controller;


use App\model\User;
use support\Cache;
use support\Request;

class LoginController extends Controller
{
    public function loginQr(){

        try {
            $clientId = uniqid();
            $response = $this->wx()->app_code->getUnlimit($clientId, [
                'page' => 'pages/confirm/confirm',
                'width' => 210,
                'env_version' => 'develop', //正式版为 release，体验版为 trial，开发版为 develop
                'check_path' => false
            ]);
            cache([$clientId=> ''], 30);
            return success('登录二维码',
                [
                    'clientId' => $clientId,
                    'qrcode' => 'data:image/png;base64,'.base64_encode($response)
                ]
            );
        } catch (\Throwable $e) {
            return error('获取二维码失败', $e->getMessage());
        }

    }

    public function hasScan(Request $request){
        $clientId = $request->input('clientId');
        if(empty($clientId)) return error('参数错误');
        return success('扫码结果', ['token' => cache($clientId), 'overdue' => !Cache::has($clientId)]);

    }

    public function login(Request $request){
        $clientId = $request->input('clientId');
        if(empty($clientId)) return error('参数错误');
        $code = $request->input('code', '');
        if(empty($code)) return error('需要code');
        $res = $this->wx()->auth->session($code);
        if(empty($res['openid'])) return error('登录失败');
        $user = User::where('openid', $res['openid'])->first();
        if(empty($user)) return error('用户不存在');
        if(!$user->is_admin) return error('您不是管理员');
        cache([$clientId => generate_user_token(['id'=>$user->id])], 30);
        return success('登录成功');
    }
}
